package com.cpic.blood.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cpic.blood.core.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @GetMapping("/upload")
    public String showUploadForm() {
        return "upload-form";
    }

    @PostMapping(value = "/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 保存上传的文件到服务器
                List<String> headers = new ArrayList<>();
                List<List<String>> dataList = new ArrayList<>();

                if (file.getOriginalFilename().endsWith(".xlsx")) {
                    // 解析 Excel 文件
                    Workbook workbook = new XSSFWorkbook(file.getInputStream());
                    Sheet sheet = workbook.getSheetAt(0);
                    Iterator<Row> rowIterator = sheet.iterator();

                    // 处理第一行作为字段
                    if (rowIterator.hasNext()) {
                        Row headerRow = rowIterator.next();
                        Iterator<Cell> cellIterator = headerRow.cellIterator();
                        while (cellIterator.hasNext()) {
                            Cell cell = cellIterator.next();
                            headers.add(cell.getStringCellValue());
                        }
                }

                    // 处理剩余行作为数据
                    while (rowIterator.hasNext()) {
                        Row dataRow = rowIterator.next();
                        List<String> rowData = new ArrayList<>();
                        Iterator<Cell> cellIterator = dataRow.cellIterator();
                        while (cellIterator.hasNext()) {
                            Cell cell = cellIterator.next();
                            rowData.add(cell.getStringCellValue());
                        }
                        dataList.add(rowData);
                    }

                    workbook.close();
                } else if (file.getOriginalFilename().endsWith(".csv")) {
                    // 解析 CSV 文件
                    BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
                    String line;
                    boolean isFirstLine = true;
                    while ((line = reader.readLine()) != null) {
                        if (isFirstLine) {
                            String[] headersArray = line.split(",");
                            headers.addAll(Arrays.asList(headersArray));
                            isFirstLine = false;
                        } else {
                            String[] dataArray = line.split(",");
                            dataList.add(Arrays.asList(dataArray));
                        }
                    }
                    reader.close();
                }

                // 读取文件内容并传递给视图进行预览
                Object json1 = JSONObject.toJSON(headers);
                Object json2 = JSONObject.toJSON(dataList);
                JSONArray array = new JSONArray();
                array.add(json1);
                array.add(json2);
                log.info(array.toJSONString());
                return R.success(array);
            } catch (IOException e) {
                e.printStackTrace();
                return R.error("An error occurred during file upload.");
            }
        } else {
            return R.error("No file selected.");
        }
    }
}
